<template>
  <div class="table-header">
    <div></div>
    <div class="table-actions">
      <el-button :icon="Refresh" @click="refresh" />
      <!-- 列选择器弹窗 -->
      <el-popover
        v-model:visible="showColumnSelector"
        placement="bottom"
        width="200"
        trigger="click"
      >
        <template #reference>
          <el-button :icon="Operation" />
          <!-- <el-button
            type="primary"
            size="small"
            @click="showColumnSelector = !showColumnSelector"
            icon="CirclePlus"
          >
            选择列
          </el-button> -->
        </template>
        <div class="column-selector">
          <h3>选择显示列</h3>
          <el-checkbox-group v-model="selectedColumns" @change="handleColumnChange">
            <el-checkbox v-for="column in allColumns" :key="column.prop" :label="column.prop">
              {{ column.label }}
            </el-checkbox>
          </el-checkbox-group>
          <div class="selector-actions">
            <el-button size="mini" @click="selectAll"> 全选 </el-button>
            <el-button size="mini" @click="deselectAll"> 全不选 </el-button>
          </div>
        </div>
      </el-popover>
    </div>
  </div>
  <el-table :data="tableData" border style="width: 100%" :scroll-x="true">
    <!-- 动态渲染选中的列 -->
    <el-table-column
      v-for="column in filteredColumns"
      :key="column.prop"
      :prop="column.prop"
      :label="column.label"
      :width="column.width"
      :align="column.align || 'left'"
      :fixed="column.prop == 'action' ? 'right' : column.prop == 'id' ? 'left' : false"
    >
      <template #default="scope">
        <div v-if="column.prop === 'action'">
          <el-button type="primary" size="small" @click="showDetil(scope.row)">详情</el-button>
          <el-button type="primary" size="small" @click="editDetil(scope.row)" v-if="isAdmin()"
            >填写利润</el-button
          >
          <el-button type="primary" size="small" @click="showAdvanceAmount(scope.row)"
            >垫付金额</el-button
          >
          <el-popconfirm
            class="box-item"
            @confirm="deleteItem(scope.row)"
            title="是否确认删除？"
            placement="top"
          >
            <template #reference>
              <el-button type="danger" size="small" v-hasPermi="['order:workorder:delete']"
                >删除</el-button
              >
            </template>
          </el-popconfirm>
        </div>
        <div v-if="column.prop === 'status'">
          {{ getDictLabel(DICT_TYPE.TICKET_STATUS, scope.row.status) }}
        </div>
      </template>
    </el-table-column>
  </el-table>
  <el-dialog
    v-model="advanceVisible"
    v-if="advanceVisible"
    title="垫付金额"
    width="500"
    top="300px"
    :before-close="handleClose"
  >
    <div>
      <el-form ref="formRef" label-width="120px" class="form-container">
        <el-row :gutter="24">
          <el-col :span="24">
            <el-form-item label="垫付金额" prop="amount">
              <el-input
                v-if="advanceVisible"
                v-model="advanceForm.amount"
                placeholder="请输入垫付金额"
              />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
    </div>
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="closeAdvance">取消</el-button>
        <el-button type="primary" @click="submitAdvance"> 提交 </el-button>
      </div>
    </template>
  </el-dialog>
  <!-- <div class="pagination">
    <el-pagination @size-change="handleSizeChange" @current-change="handleCurrentChange" :current-page="currentPage"
      :page-sizes="[10, 20, 50]" :page-size="pageSize" layout="->,total, sizes, prev, pager, next, jumper"
      :total="121" />
  </div> -->
  <Detil ref="detilRef" />
  <DuringRecyclingEdit ref="duringRecyclingRef" @onSubmit="getList" />
</template>

<script setup>
import { ref, reactive, computed, defineExpose } from 'vue'
import Detil from '../components/Detil.vue'
import DuringRecyclingEdit from '../components/DuringRecyclingEdit.vue'
import * as advanceHistoryApi from '@/api/order/advanceHistory/index'
import * as ticketManagementApi from '@/api/ticketManagement/index'
import {
  Check,
  Delete,
  Edit,
  Message,
  Search,
  Star,
  Refresh,
  Operation,
  Expand,
  Plus
} from '@element-plus/icons-vue'
import { getDictLabel, DICT_TYPE } from '@/utils/dict'
import { isAdmin } from '@/utils/tool'
import { ElMessage } from 'element-plus'
const detilRef = ref(null)
const duringRecyclingRef = ref(null)
const advanceVisible = ref(false) // 垫付弹窗
const advanceForm = ref({
  advanceAmount: ''
})
const id = ref('')
onMounted(() => {
  console.log('--->', isAdmin())
  getList()
})
const getList = (data) => {
  const formData = data ? JSON.parse(JSON.stringify(data)) : {}
  formData.status = 3
  ticketManagementApi.getWorkorder(formData).then((res) => {
    console.log(res);
    tableData.value = res
  })
}
// 刷新
const refresh = () => {
  getList()
  ElMessage.success('刷新成功')
}
const onSubmit = () => {
  getList()
}
// 列选择器显示状态
const showColumnSelector = ref(false)
// 定义所有可用列
const allColumns = ref([
  { prop: 'id', label: '工单编号', width: 190, align: 'center', fixed: 'left' },
  { prop: 'createName', label: '跟单员', width: 120, align: 'center' },
  { prop: 'customerName', label: '客户名称', width: 120, align: 'center' },
  { prop: 'customerReceiveNo', label: '寄出单号', width: 190, align: 'center' },
  { prop: 'customerSendNo', label: '回收单号', width: 190, align: 'center' },
  { prop: 'customerPhone', label: '客户手机号', width: 130, align: 'center' },
  { prop: 'sourceDate', label: '来源日期', width: 120, align: 'center' },
  { prop: 'platformName', label: '平台', width: 100, align: 'center' },
  { prop: 'source', label: '来源', width: 130, align: 'center' },
  { prop: 'enterpriseNo', label: '企业号', width: 180, align: 'center' },
  { prop: 'status', label: '工单状态', width: 120, align: 'center' },
  { prop: 'action', label: '操作', width: isAdmin() ? 330 : 280, align: 'center', fixed: 'right' }
])
// 表格数据（模拟）
const tableData = ref([])
// 选中的列 (初始选择所有列)
const selectedColumns = ref(allColumns.value.map((col) => col.prop))
// 过滤出选中的列
const filteredColumns = computed(() => {
  return allColumns.value.filter((col) => selectedColumns.value.includes(col.prop))
})
// 处理列选择变化
const handleColumnChange = (values) => {
  // 至少保留一列
  if (values.length === 0) {
    selectedColumns.value = [allColumns.value[0].prop]
  }
  // 这里可以添加保存到本地存储的逻辑
  localStorage.setItem('tableColumns', JSON.stringify(selectedColumns.value))
}

// 全选
const selectAll = () => {
  selectedColumns.value = allColumns.value.map((col) => col.prop)
  handleColumnChange(selectedColumns.value)
}

// 全不选
const deselectAll = () => {
  selectedColumns.value = []
  handleColumnChange(selectedColumns.value)
}
// 分页数据
const currentPage = ref(1)
const pageSize = ref(10)

// 打开详情
const showDetil = (row) => {
  ticketManagementApi.detilWorkorder(row.id).then((res) => {
    console.log('resss', res)
    detilRef.value.onOpen(res)
  })
}
// 打开编辑弹窗
const editDetil = (row) => {
  ticketManagementApi.detilWorkorder(row.id).then((res) => {
    duringRecyclingRef.value.onOpen(JSON.parse(JSON.stringify(res)))
  })
}
// 垫付金额
const showAdvanceAmount = (row) => {
  id.value = row.id
  advanceVisible.value = true
}
// 提交垫付金额
const submitAdvance = () => {
  advanceForm.value.orderNo = id.value
  advanceHistoryApi.addAdvanceHistory(advanceForm.value).then((res) => {
    advanceVisible.value = false
    ElMessage.success('提交成功')
    getList()
    advanceForm.value.amount = ''
  })
}
// 关闭弹窗
const closeAdvance = () => {
  advanceVisible.value = false
  advanceForm.value.advanceAmount = ''
}
// 删除
const deleteItem = (row) => {
  ticketManagementApi.delWorkorder(row.id).then(() => {
    ElMessage({
      message: '删除成功',
      type: 'success'
    })
    getList()
  })
}
const handleSizeChange = (val) => {
  pageSize.value = val
}

const handleCurrentChange = (val) => {
  currentPage.value = val
}

defineExpose({
  getList
})
</script>
<style scoped lang="scss">
.table-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 10px;
}

.table-actions {
  display: flex;
}

.pagination {
  margin-top: 15px;
  text-align: right;
}
</style>
